function friendlyDate(_timestamp) {
  let timestamp = _timestamp * 1000;
  let formats = {
    'year': '%n%年前',
    'month': '%n%月前',
    'day': '%n%天前',
    'hour': '%n%小时前',
    'minute': '%n%分钟前',
    'second': '%n%秒前',
  };

  let now = Date.now();
  let seconds = Math.floor((now - timestamp) / 1000);
  let minutes = Math.floor(seconds / 60);
  let hours = Math.floor(minutes / 60);
  let days = Math.floor(hours / 24);
  let months = Math.floor(days / 30);
  let years = Math.floor(months / 12);

  let diffType = '';
  let diffValue = 0;
  if (years > 0) {
    diffType = 'year';
    diffValue = years;
  } else {
    if (months > 0) {
      diffType = 'month';
      diffValue = months;
    } else {
      if (days > 0) {
        diffType = 'day';
        diffValue = days;
      } else {
        if (hours > 0) {
          diffType = 'hour';
          diffValue = hours;
        } else {
          if (minutes > 0) {
            diffType = 'minute';
            diffValue = minutes;
          } else {
            diffType = 'second';
            diffValue = seconds === 0 ? (seconds = 1) : seconds;
          }
        }
      }
    }
  }
  return formats[diffType].replace('%n%', diffValue);
}

// 时间转换为时间戳
function formtimestamp(_time) {
  let temp = _time.replace(/\-/g, '/');
  temp = temp.replace(/\_/g, ' ');
  return Date.parse(temp) / 1000;
}

/**
 * 格式化日期为指定格式的字符串
 * @param {string|Date} input - 日期字符串（ISO格式）或Date对象
 * @param {string} format - 日期格式，默认为'YYYY-MM-DD HH:mm:ss'
 * @returns {string} - 格式化后的日期字符串
 */
function formatDate(input, format = 'YYYY-MM-DD HH:mm:ss') {
  let date;

  if (input instanceof Date) {
    date = input;
  } else if (typeof input === 'string') {
    date = new Date(input);
    // 检查是否是ISO格式，如果不是，尝试解析
    if (isNaN(date.getTime())) {
      throw new Error('Invalid date string');
    }
  } else {
    throw new Error('Invalid input type. Expected string or Date.');
  }

  const YYYY = date.getFullYear();
  const MM = ('0' + (date.getMonth() + 1)).slice(-2);
  const DD = ('0' + date.getDate()).slice(-2);
  const HH = ('0' + date.getHours()).slice(-2);
  const mm = ('0' + date.getMinutes()).slice(-2);
  const ss = ('0' + date.getSeconds()).slice(-2);

  return format
    .replace('YYYY', YYYY)
    .replace('MM', MM)
    .replace('DD', DD)
    .replace('HH', HH)
    .replace('mm', mm)
    .replace('ss', ss);
}

export {friendlyDate, formtimestamp, formatDate}
